package com.atguigu.tingshu.search.consumer;

import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/***
 * 接收专辑ID
 */
@Component
@Log4j2
public class AlbumConsumer {
    @Autowired
    private ItemService itemService;

    //监听的上架消息队列
    @SneakyThrows
    @RabbitListener(queues = "AlbumA_Search_upper_queue")
    public void albumUpperConsumer(Channel channel , Message message){
        //接收队列消息
        byte[] body = message.getBody();
        Long albumId = Long.valueOf(new String(body));
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //上架
            itemService.addAlbumFromMysql( albumId);
            //手动确认消息
            channel.basicAck(deliveryTag,false);
            //判断是否第一次
        } catch (IOException e) {
            if (messageProperties.getRedelivered()){
                log.error("上架消息失败，专辑ID："+albumId+
                        "失败原因是："+ e.getMessage());
                //不是就记录日志丢弃
                channel.basicReject(deliveryTag,false);
        }else {
                //是第一次就放回去再来一次
                channel.basicReject(deliveryTag,true);
            }
        }
    }

    //监听的下架消息队列
    @SneakyThrows
    @RabbitListener(queues = "AlbumA_Search_Down_queue")
    public void albumDownConsumer(Channel channel , Message message){
        //接收队列消息
        byte[] body = message.getBody();
        Long albumId = Long.valueOf(new String(body));
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //上架
            itemService.removeAlbumFrommysql( albumId);
            //手动确认消息
            channel.basicAck(deliveryTag,false);
            //判断是否第一次
        } catch (IOException e) {
            if (messageProperties.getRedelivered()){
                log.error("下架消息失败，专辑ID："+albumId+
                        "失败原因是："+ e.getMessage());
                //不是就记录日志丢弃
                channel.basicReject(deliveryTag,false);
                System.out.println(e.getMessage());
            }else {
                //是第一次就放回去再来一次
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
